package com.commons.tools.utils;

/**
 * @Description: 电话号码工具类
 * @author: Destin
 * @date: 2023-03-07
 */

import cn.hutool.core.util.*;
import com.google.i18n.phonenumbers.*;
import com.google.i18n.phonenumbers.Phonenumber.*;
import com.google.i18n.phonenumbers.geocoding.*;

import java.util.*;

public class PhoneUtil {

    private static PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();

    private static PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance();

    public static final int CHINA_COUNTRY_CODE = 86;

    public static final String PROVINCE_REG = "[\\u4E00-\\u9FFF]+?(?:省|自治区|特别行政区)|(?:天津|重庆|上海|北京)市";
    public static final String CITY_REG = "(?<=省|自治区|特别行政区)[\u4E00-\u9FFF]+?(?:市|自治州|区|县|盟)";

    /**
     * 根据国家代码和手机号  判断手机号是否有效
     * phoneNumber
     * countryCode
     * 手机号是否有效
     */
    public static boolean checkPhoneNumber(String phoneNumber, String countryCode) {
        int ccode = NumberUtil.parseInt(countryCode);
        long phone = NumberUtil.parseLong(phoneNumber);
        PhoneNumber pn = new PhoneNumber();
        pn.setCountryCode(ccode);
        pn.setNationalNumber(phone);
        return phoneNumberUtil.isValidNumber(pn);

    }

    /**
     * 获取归属地
     */
    public static String getGeo(String phoneNumber, Integer countryCode) {
        long phone;
        try {
            phone = NumberUtil.parseLong(phoneNumber);
        } catch (Exception e) {
            return "";
        }
        PhoneNumber pn = new PhoneNumber();
        pn.setCountryCode(countryCode);
        pn.setNationalNumber(phone);
        return geocoder.getDescriptionForNumber(pn, Locale.CHINESE);
    }

    //获取归属地，中国
    public static String getGeo(String phoneNumber) {
        return getGeo(phoneNumber, CHINA_COUNTRY_CODE);
    }

    public static Area getArea(String phoneNumber) {
        String address = getGeo(phoneNumber);
        if (StrUtil.isNotEmpty(address)) {
            String province = ReUtil.getGroup0(PROVINCE_REG, address);
            String city = ReUtil.getGroup0(CITY_REG, address);
            Area area = new Area();
            area.setProvince(province);
            area.setCity(city);
            return area;

        }
        Area area = new Area();
        area.setProvince("未知");
        area.setCity("未知");
        return area;
    }

    public static class Area {
        private String province;
        private String city;

        public String getProvince() {
            return province;
        }

        public void setProvince(String province) {
            this.province = province;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }
    }

}